<template>
    <el-dialog v-model="isDialogFormVisible" :title="dialogTitle">
        <el-form ref="ruleFormRef" :rules="rules" @submit.native.prevent :model="editItem">
            <span v-for="item in props.bgcolumnNames">
                <!-- Readonly display: label + plain text value -->
                <el-form-item v-if="props.readonly" :label="item.Label">
                    <div class="readonly-value">{{ formatDisplayValue(item) }}</div>
                </el-form-item>
                <!-- Editable controls -->
                <el-form-item v-else-if="item.IsEditable" :label="item.Label" :prop="item.Name">
                    <span v-if="item.ControlType == 1">
                        <JSCodeMirror v-model:value="editItem[item.Name]"></JSCodeMirror>
                    </span>
                    <el-input-number v-else-if="item.ControlType == 2" v-model="editItem[item.Name]" class="mx-4"
                        controls-position="right" />
                    <el-switch  v-else-if="item.TypeName == 'Boolean'" v-model="editItem[item.Name]" class="mx-4" />

                    <el-date-picker v-else-if="item.TypeName == 'DateTime'" v-model="editItem[item.Name]" type="date"
                        :shortcuts="[{ text: 'Today', value: new Date() }]" value-format="YYYY-MM-DD"
                        placeholder="Pick a day" />
                    <el-select v-else-if="item.ControlType == 7" @change="selectChange(item)"
                        v-model="editItem[item.Name]" placeholder="请选择">
                        <el-option v-for="(label, value) in item.EnumDic" :label="label" :value="Number(value)" />
                    </el-select>
                    <el-input v-else v-model="editItem[item.Name]" :type="item.Name==='Password' ? 'password' : 'text'" autocomplete="off" />

                </el-form-item>
            </span>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">{{ props.readonly ? '关闭' : '取消' }}</el-button>
                <el-button v-if="!props.readonly" type="primary" @click="onConfirm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import JSCodeMirror from '../components/JSCodeMirror.vue'; // 引入 CodeEditor 组件
import type { ElForm, FormInstance, FormRules } from 'element-plus'
import moment from 'moment';

const isDialogFormVisible = ref(false)
const ruleFormRef = ref(null)
var editItem = reactive({});
const emit = defineEmits(['confirm', 'selectChange']);
const rules = reactive({})

// props 接收父组件传过来的
const props = defineProps({
    bgcolumnNames: Array as () => any[],
    readonly: { type: Boolean, default: false }
})
const dialogTitle = computed(() => {
    if (props.readonly) return '查看'
    const id = (editItem as any)?.Id
    return !id || Number(id) === 0 ? '新增' : '编辑'
})
const close = () => {
    isDialogFormVisible.value = false
}
const selectChange = (colItem) => {
    emit("selectChange", editItem, colItem)
}

const open = (item) => {
    isDialogFormVisible.value = true

    props.bgcolumnNames.forEach(item => {
        //不可为空
        if (!item.IsNullable) {
            rules[item.Name] = [
                { required: true, message: `请输入${item.Label}`, trigger: 'blur' }
            ]
        }
    })

    editItem = reactive(item)
    // userName 必填的兜底（若后端未标注非空）
    if (!rules['UserName']) {
        rules['UserName'] = [{ required: true, message: '请输入UserName', trigger: 'blur' }]
    }
}
var onConfirm = async (formEl: FormInstance | undefined) => {
    await ruleFormRef.value.validate()
    emit("confirm", editItem)
}

const formatDisplayValue = (colItem: any) => {
    const value = (editItem as any)[colItem.Name]
    if (value === null || value === undefined || value === '') return '-'

    if (colItem.ControlType == 7 && colItem.EnumDic) {
        const mapped = colItem.EnumDic[value] ?? colItem.EnumDic[String(value)]
        return mapped ?? value
    }
    if (colItem.TypeName === 'Boolean') {
        return value ? '是' : '否'
    }
    if (colItem.TypeName === 'DateTime') {
        const m = moment(value)
        return m.isValid() ? m.format('YYYY-MM-DD HH:mm:ss') : value
    }
    // 长文本换行显示
    return String(value)
}

defineExpose({ open, close });

</script>
<style>
.el-form-item__label{
    width: 15%;
}
.readonly-value{
    white-space: pre-wrap;
    word-break: break-word;
}
</style>
